package com.powerhua.oa.assistant.meeting;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.powerhua.core.base.dao.CommonDao;
import com.powerhua.core.utils.CommonUtils;

public class MeetingRoomSelectorDao extends CommonDao {

	private static final Log LOG = LogFactory
			.getLog(MeetingRoomSelectorDao.class);

	@SuppressWarnings("unchecked")
	public String listAll(Date date) {
		StringBuffer result = new StringBuffer("");

		Map roomMap = new HashMap();
		Map roomTimeMap = new HashMap();
		String sql = "select id_,name_ from tb_meetingroom";
		List roomList = jdbcTemplate.queryForList(sql);
		Iterator itr = roomList.iterator();
		while (itr.hasNext()) {
			Map map = (Map) itr.next();
			String roomName = (String) map.get("name_");
			String roomId = (String) map.get("id_");
			roomMap.put(roomId, roomName);
			roomTimeMap.put(roomId, "");
		}

		String dateStr = CommonUtils.getDateFormat(new Timestamp(date.getTime()));
		sql = "select b.meeting_room_id_,b.time_ from tb_meeting a, tb_meeting_room b "
				+ " where a.id_=b.meeting_id_ and a.date_ between '" + dateStr + " 00:00:00" + "' and '" + dateStr + " 23:59:59" + "' order by time_";
		List list = jdbcTemplate.queryForList(sql);
		itr = list.iterator();
		while (itr.hasNext()) {
			Map map = (Map) itr.next();
			String roomId = (String) map.get("meeting_room_id_");
			String roomTime = (String) map.get("time_");
			String roomTimes = (String) roomTimeMap.get(roomId);
			if ("".equals(roomTimes)) {
				roomTimes += "'" + roomTime + "'";
			} else {
				roomTimes += ",'" + roomTime + "'";
			}
			roomTimeMap.put(roomId, roomTimes);
		}

		itr = roomTimeMap.keySet().iterator();
		int j = 0;
		result = new StringBuffer("[");
		while (itr.hasNext()) {
			String key = (String) itr.next();
			if (j != 0) {
				result.append(",");
			}
			result.append("['");
			result.append(key);
			result.append("','");
			result.append(roomMap.get(key));
			result.append("'");
			if(!"".equals(roomTimeMap.get(key))) {
				result.append(",");
				result.append(roomTimeMap.get(key));
			} 
			result.append("]");		

			j++;
		}

		result.append("]");
		return result.toString();
	}

}
